/* $RCSFile: PrivateDocXmlFeeder.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.EMailing/PageModules/DownloadSession/PrivateDocXmlFeeder.ascx.cs $
 * $log$
 * Revision 23 2010/08/09 11:12:45  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 10 2010/08/09 10:13:18  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Data;
using System.Drawing;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.Globalization;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;

using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;

using AddonNice.CRMWrapper;

using AddonNice.CRMEMailing;
using AddonNice.CRMEMailing.Settings.UI.WebControls;
using AddonNice.Settings.CRMEMailing;
using AddonNice.CRMWrapper.CRMEMailing;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.DownloadSession
{
    /// <summary>
    /// Initializer class for PrivateDocXmlFeeder 
    /// </summary>
    public class PrivateDocXmlFeederSI : PrivateDocFeeder0SI
    {
        public PrivateDocXmlFeederSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base(bSettings,pm)
        {
            if ( PrivateDocFeederTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDocXmlFeederSI Ctor BEG.",PrivateDocFeederTrace.Sw.Info);
            InitSettings(bSettings,pm);
            if ( PrivateDocFeederTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDocXmlFeederSI Ctor END.",PrivateDocFeederTrace.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( PrivateDocFeederTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDocXmlFeederSI InitSettings BEG.",PrivateDocFeederTrace.Sw.Info);
            
            base.InitSettings(bSettings,pm);

           
            if ( PrivateDocFeederTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDocXmlFeederSI InitSettings END.",PrivateDocFeederTrace.Sw.Info);
        }
 
    }

    /// <summary>
    /// From a folder, a campaign, a marketinglist read documents in a folder and generates privateDocuments entities related to current campaign
    /// Also fill a table to accelerate the sending of bulk emails referencing privatedocuments, as we need to send the private document id for each mail we will access them with the the sessionid, the listuserid
    /// </summary>
    public partial class PrivateDocXmlFeeder : PrivateDocFeeder0
    {
        #region General implementation
        
        public override Guid GuidID
        {
            get
            {
                return new Guid(AStr.PrivateDocXmlFeederGuid);
            }
        }
        #endregion General implementation

        
        public PrivateDocXmlFeeder()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDocXmlFeeder Ctor Called.",ModuleTraceSwitch.Sw.Info);
            // Validators : name Ok
            ValidationGroup                     =   "Main";

        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                 =   "PRIVATEDOCXMLFEEDER";
                return extgrp;
            }
		}
         
        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new PrivateDocXmlFeederSI(bSettings,this);
        }

    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose | PrivateDocFeederTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PrivateDocXmlFeeder Page_Load isPostBack: {0}",IsPostBack),(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:PrivateDocFeederTrace.Sw.Info);
            const string fmt                        =   "realPostBack('{0}', ''); return false;";
            updateBtn.OnClientClick                 =   string.Format(fmt, updateBtn.UniqueID);
            if (!IsPostBack)
            {
            }
        }

        /*
         * Xml file Format
         * <PrivDoc>
         * <Title />
         * <FileName />
         * <FileUrl />
         * <SchemaName />
         * <ID />
         * <Name />
         * </PrivDoc>
         * 
         */
        void FillFromXml(Guid SessionId)
        {
            string path                         =   ImportFileName.Text;
            XDocument doc                       =   XDocument.Load(path);
            var privdocs = from d in doc.Descendants("PrivDoc") 
                                select new
                                { 
                                title       =   d.Element("Title").Value,
                                filename    =   d.Element("Filename").Value,
                                fileurl     =   d.Element("FileUrl").Value,
                                schema      =   d.Element("SchemaName").Value,
                                id          =   (d.Element("ID") != null ) ? d.Element("ID").Value:string.Empty,
                                name        =   d.Element("Name").Value
                                };


            foreach ( var e in privdocs )
            {
                bool created                    =   false;
                if ( File.Exists(e.fileurl) )
                {
                    InternalQueryExpression qe  =   new InternalQueryExpression();
                    qe.ColumnSet                =   new InternalAllColumns();
                    qe.EntityName               =   AStr.adnprivatedocument;
                    qe.Criteria                 =   new InternalFilterExpression();
                    InternalConditionExpression ce =   new InternalConditionExpression();
                    if ( e.id != string.Empty )
                    {
                        switch ( e.schema )
                        {
                            case CrmStr.account:
                            ce.AttributeName = CrmStr.accountid;
                            break;
                            case CrmStr.contact:
                            ce.AttributeName = CrmStr.contactid;
                            break;
                            case CrmStr.lead:
                            ce.AttributeName = CrmStr.leadid;
                            break;
                        }
                        ce.Operator = InternalConditionOperator.Equal;
                        ce.Values = new string[] { e.id };
                    }
                    else
                    {
                        switch ( e.schema )
                        {
                            case CrmStr.account:
                            ce.AttributeName = CrmStr.name;
                            break;
                            case CrmStr.contact:
                            ce.AttributeName = CrmStr.fullname;
                            break;
                            case CrmStr.lead:
                            ce.AttributeName = CrmStr.fullname;
                            break;
                        }
                        ce.Operator = InternalConditionOperator.Equal;
                        ce.Values = new string[] { e.name };
                    }
                    InternalConditionExpression ce2 =   new InternalConditionExpression();
                    ce2.AttributeName           =   AStr.adndownloadsessionid;
                    ce2.Operator                =    InternalConditionOperator.Equal;
                    ce2.Values                  =   new string[] { SessionId.ToString()};
                    qe.Criteria.Conditions      =   new InternalConditionExpression[]{ce,ce2};
                    int count                   =   0;
                    ADNDynPrivateDocument priv  =   Wrapper.Util.FindEntityByQuery<ADNDynPrivateDocument>(AStr.adnprivatedocument,qe,ResetWrapper,ref count,true,null);
                    if ( priv == null )
                    {
                        priv                    =   new ADNDynPrivateDocument(ResetWrapper,e.title);
                        priv.adnfilename        =   e.filename;
                        ADNDynCustomer dynCust  =   null;
                        int cnt                 =   0;
                        switch ( e.schema )
                        {
                            case CrmStr.account:
                            if ( e.id != string.Empty )
                                dynCust         =   DynEntity.GetFromCache<ADNDynAccount>(CrmStr.account,Wrapper,ResetWrapper,new Guid(e.id));
                            else dynCust        =   Wrapper.Util.FindAccountByName(e.name,false,ref created);
                            break;
                            case CrmStr.contact:
                            if ( e.id != string.Empty )
                                dynCust         =   DynEntity.GetFromCache<ADNDynContact>(CrmStr.contact,Wrapper,ResetWrapper,new Guid(e.id));
                            else dynCust        =   Wrapper.Util.FindEntityByStringField<ADNDynContact>(CrmStr.contact,CrmStr.fullname,e.name,ResetWrapper,ref cnt,true,null);
                            break;
                            case CrmStr.lead:
                            if ( e.id != string.Empty )
                                dynCust         =   DynEntity.GetFromCache<ADNDynLead>(CrmStr.lead,Wrapper,ResetWrapper,new Guid(e.id));
                            else dynCust        =   Wrapper.Util.FindEntityByStringField<ADNDynLead>(CrmStr.lead,CrmStr.fullname,e.name,ResetWrapper,ref cnt,true,null);
                            break;
                        }
                        if ( dynCust != null )
                            switch ( e.schema )
                            {
                                case CrmStr.account:
                                priv.adnaccountid    =   dynCust.PrimaryKeyGuidValue;
                                break;
                                case CrmStr.contact:
                                priv.adncontactid   =   dynCust.PrimaryKeyGuidValue;
                                break;
                                case CrmStr.lead:
                                priv.adnleadid      =   dynCust.PrimaryKeyGuidValue;
                                break;
                            }
                        priv.adncategory        =   1;
                        priv.adnfileurl         =   e.fileurl;
                        priv.adndownloadsessionid   =   SessionId;
                        priv.adndownloadcount   =   0;
                        priv.Create();
                        created                 =   true;
                    }
                    LoadFile(priv,e.fileurl,e.title,e.filename,created);
                }
            }
        }


        void PrivateDocXmlFeeder_ADNUpdateModule(object sender, ModuleEventArgs e)
        {
            // Should Email contain values
            if (!Page.IsValid)
            {
                if (PrivateDocFeederTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( "[V]PrivateDocXmlFeeder PrivateDocXmlFeeder_ADNUpdateModule : Page not valid",PrivateDocFeederTrace.Sw.Info);
                return;
            }

            if ( string.IsNullOrEmpty(CbDownloadSession.SelectedValue) )
                return;

            // Update or Add new entity to Crm
            try
            {
                Guid DwnSessionId       =   new Guid(CbDownloadSession.SelectedValue);
                FillFromXml(DwnSessionId);
            }
            catch (Exception ex)
            {
                if (PrivateDocFeederTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]PrivateDocXmlFeeder PrivateDocXmlFeeder_ADNUpdateModule  ex: {0}", ex),PrivateDocFeederTrace.Sw.Info);
                throw;
            }
        }

        #region Std overrides

        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            updateBtn.SkinID        =   "Update_" + Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            BtnChooseFile.SkinID    =   "Open_"+ Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
        }

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            Load                                        +=  new System.EventHandler(Page_Load);
            ADNUpdateModule                             +=  new PortalModuleEventHandler(PrivateDocXmlFeeder_ADNUpdateModule);
            CbDownloadSession.WebServiceSettings.Method =   "GetDownloadSessions";
            CbDownloadSession.WebServiceSettings.Path   =   "/Services/XrmEmailing.asmx";

            CbDownloadSession.WebServiceMethod          =   "GetDownloadSessions";
            CbDownloadSession.WebServicePath            =   "/Services/XrmEmailing.asmx";
        }

        #endregion Std overrides
    }
}